package com.ruoyi.school.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.school.convert.PacClassConverter;
import com.ruoyi.school.domain.*;
import com.ruoyi.school.domain.vo.PacClassInfoVo;
import com.ruoyi.school.domain.vo.PacClassTeacherInfoVo;
import com.ruoyi.school.enums.RoleTypeEnum;
import com.ruoyi.school.service.PacClassService;
import com.ruoyi.school.mapper.PacClassMapper;
import com.ruoyi.school.service.PacClassTeacherService;
import com.ruoyi.school.service.PacFacultiesService;
import com.ruoyi.school.service.PacTeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.ruoyi.common.utils.PageUtils.startPage;
import static com.ruoyi.common.utils.SecurityUtils.getLoginUser;

/**
 * @author jeremylin
 * @description 针对表【pac_class(班级表)】的数据库操作Service实现
 * @createDate 2025-05-25 16:40:43
 */
@Service
public class PacClassServiceImpl extends ServiceImpl<PacClassMapper, PacClass>
        implements PacClassService {
    @Resource
    private PacFacultiesService facultiesService;

    @Resource
    private PacTeacherService pacTeacherService;

    @Resource
    private PacClassMapper pacClassMapper;

    @Resource
    private PacClassTeacherService pacClassTeacherService;

    /**
     * 查询老师绑定的班级信息
     *
     * @param user
     * @return
     */
    @Override
    public List<PacClass> selectByTeacher(SysUser user) {
        Long userId = user.getUserId();
        PacTeacher byUserId = pacTeacherService.getByUserId(userId);
        if (byUserId == null) return null;
        List<PacClass> list = lambdaQuery().eq(PacClass::getBindTeacher, byUserId.getId()).list();
        return list;
    }

    /**
     * 绑定班级
     * 1、专业老师，可无限绑定
     * 2、学业老师，只可绑定一个
     *
     * @param pacClass
     */
    @Override
    public void bindClass(PacClass pacClass) {
        // 拿到登陆人的信息
        LoginUser loginUser = getLoginUser();
        SysUser user = loginUser.getUser();
        // 查询老师信息
        PacTeacher teacher = pacTeacherService.getByUserId(user.getUserId());
        // 判断他的角色是有含有教师
        List<String> roleKeys = user.getRoles().stream().map(SysRole::getRoleKey).collect(Collectors.toList());
        boolean contains = roleKeys.contains(RoleTypeEnum.TEACHER.getName());
        boolean contains2 = roleKeys.contains(RoleTypeEnum.TEACHER2.getName());
        boolean contains3 = roleKeys.contains(RoleTypeEnum.CAPTAIN.getName());

        if (!contains && !contains2 && !contains3) {
            throw new RuntimeException("无可绑定角色");
        }

        if(pacClass.getRoleKey().isEmpty()){
            throw new BaseException("请选择绑定角色");
        }
        pacClass.setBindTeacher(user.getUserId().intValue());
        // 查询学院名字
        PacFaculties byId = facultiesService.getById(pacClass.getFacultiesId());
        pacClass.setFacultiesName(byId.getFacultiesName());
        updateById(pacClass);
        // 插入关系表

        List<SysRole> roles = user.getRoles();
        if (!roles.isEmpty()) {
            //绑定角色
            PacClassTeacher pacClassTeacher = new PacClassTeacher();
            pacClassTeacher.setClassId(pacClass.getId());
            pacClassTeacher.setTeacherId(teacher.getId());

            // 查找角色（使用orElse(null)避免NoSuchElementException）

//            SysRole sysRole = roles.stream()
//                    .filter(item -> item.getRoleKey().equals(RoleTypeEnum.TEACHER.getName()))
//                    .findFirst()
//                    .orElse(null);

            String roleKey = pacClass.getRoleKey();
            // 先判断是否已存在相同记录
            if (!existsByUniqueKey(pacClass.getId(), teacher.getId(), roleKey)) {
                pacClassTeacher.setRoleKey(roleKey);
                pacClassTeacherService.save(pacClassTeacher);
            }else{
                throw new RuntimeException("当前角色已绑定该班级");
            }

//            // 处理第二个角色插入
//            PacClassTeacher pacClassTeacher2 = new PacClassTeacher();
//            pacClassTeacher2.setClassId(pacClass.getId());
//            pacClassTeacher2.setTeacherId(teacher.getId());
//
//            SysRole sysRole2 = roles.stream()
//                    .filter(item -> item.getRoleKey().equals(RoleTypeEnum.TEACHER2.getName()))
//                    .findFirst()
//                    .orElse(null);
//
//            if (sysRole2 != null) {
//                String roleKey2 = sysRole2.getRoleKey();
//                // 同样判断是否已存在
//                if (!existsByUniqueKey(pacClass.getId(), teacher.getId(), roleKey2)) {
//                    pacClassTeacher2.setRoleKey(roleKey2);
//                    pacClassTeacherService.save(pacClassTeacher2);
//                }
//            }

        }

    }

    // 抽取判断是否存在的方法（可放在Service层）
    private boolean existsByUniqueKey(Integer classId, Integer teacherId, String roleKey) {
        LambdaQueryWrapper<PacClassTeacher> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PacClassTeacher::getClassId, classId)
                .eq(PacClassTeacher::getTeacherId, teacherId)
                .eq(PacClassTeacher::getRoleKey, roleKey);
        return pacClassTeacherService.count(queryWrapper) > 0;
    }

    /**
     * 模糊查询,未被我绑定的班级信息
     *
     * @param pacClass
     * @return
     */
    @Override
    public List<PacClass> getNoBindAllByName(PacClass pacClass) {
        if (Objects.isNull(pacClass.getFacultiesId())) {
            throw new RuntimeException("请选择所属院系");
        }

        LoginUser loginUser = getLoginUser();
        PacTeacher byUserId = pacTeacherService.getByUserId(loginUser.getUser().getUserId());
        List<PacClass> list = pacClassMapper.selectUnboundClasses(byUserId.getId(), pacClass.getClassName(), pacClass.getFacultiesId(),pacClass.getRoleKey());
        return list;
    }

    /**
     * 查询班级详细信息
     *
     * @param classIds
     * @return
     */
    @Override
    public List<PacClassInfoVo> selectClassTeacherByIds(List<Long> classIds) {
        if (!classIds.isEmpty()) {
            List<PacClass> list = lambdaQuery()
                    .in(PacClass::getId, classIds)
                    .list();
            List<Integer> teacherIds = list.stream().map(PacClass::getBindTeacher).collect(Collectors.toList());
            List<PacTeacher> teachers = pacTeacherService.getTeacherListByUserIds(teacherIds);
            Map<Integer, PacTeacher> teacherMap = teachers.stream().collect(Collectors.toMap(PacTeacher::getUserId, Function.identity()));

            List<PacClassInfoVo> pacClassInfoVos = PacClassConverter.INSTANCE.PacClassList2PacClassInfoVoList(list);
            pacClassInfoVos.forEach(item -> {
                PacTeacher teacher = teacherMap.get(item.getBindTeacher());
                if (teacher != null) {
                    item.setTeacherName(teacher.getTeacherName());
                }
            });
            return pacClassInfoVos;
        }
        return new ArrayList<>();
    }

    /**
     * 根据班级名称查找
     *
     * @param stuClass
     * @return
     */
    @Override
    public PacClass getInfoByClassName(String stuClass) {
        if (StringUtils.isEmpty(stuClass)) {
            return null;
        }
        PacClass pacClass = lambdaQuery()
                .eq(PacClass::getClassName, stuClass)
                .one();
        return pacClass;
    }

    @Override
    public List<PacClass> getList(PacClass pacClass) {
        List<PacClass> list = lambdaQuery()
                .eq(Objects.nonNull(pacClass.getFacultiesId()), PacClass::getFacultiesId, pacClass.getFacultiesId())
                .eq(Objects.nonNull(pacClass.getCollegeId()), PacClass::getCollegeId, pacClass.getCollegeId()).list();
        return list;
    }

    @Override
    public PacClass getDetails(PacClass pacClass) {
        if (pacClass.getId() == null) {
            throw new RuntimeException("id不能为空");
        }
        return getById(pacClass.getId());
    }

    @Override
    public boolean add(PacClass pacClass) {
        if(save(pacClass)){
            return true;
        }
        return false;
    }

    @Override
    public boolean edit(PacClass pacClass) {
        if (updateById(pacClass)) {
            return true;
        }
        return false;
    }

    @Override
    public boolean delete(PacClass pacClass) {
        if (pacClass.getId() == null) {
            throw new RuntimeException("id不能为空");
        }
        if (removeById(pacClass.getId())) {
            return true;
        }
        return false;
    }

    @Override
    public List<PacClass> getAllList(PacClass pacClass) {
        return lambdaQuery().list();
    }
}




